package ai.nlp;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 根据自然语言调用接口
 */
public class NaturalLanguageQuery2 {

    static String userInput1 = "请查询最近3天内编号为10300101的告警记录";
    static String userInput2 = "帮忙查下最近1周内编号是1111的告警信息";
    static String userInput3 = "检索最近3月id是10300101的告警信息";
    static String userInput4 = "帮忙查下告警信息";

    public static void main(String[] args) {
        query0("帮忙查下最近1周内编号是1111的告警信息\"");
    }

    private static void query0(String input) {

        try {
            QueryParams params = parseInput(input);
            String apiUrl = buildApiUrl(params);
            System.out.println("生成的API地址: " + apiUrl);

            //String response = callApi(apiUrl);
            //System.out.println("\n接口响应结果:\n" + response);
        } catch (IllegalArgumentException e) {
            System.err.println("输入解析错误: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("系统错误: " + e.getMessage());
        }
    }


    private static QueryParams parseInput(String input) {
        List<Term> terms = HanLP.segment(input);
        System.out.println("【分词结果】" + terms);

        // 验证查询类型
        if (!isAlarmQuery(terms)) {
            throw new IllegalArgumentException("请给出更具体的信息，比如：您可以说：查询最近3天内编号是1111的告警信息");
        }

        // 提取订单编号
        String orderId = extractOrderId(input);
        if (orderId == null) {
            throw new IllegalArgumentException("未找到有效的订单编号");
        }

        // 解析时间范围
        DateRange dateRange = parseDateRange(input);
        if (dateRange == null) {
            throw new IllegalArgumentException("未识别到有效的时间范围");
        }

        return new QueryParams(orderId, dateRange);
    }

    private static boolean isAlarmQuery(List<Term> terms) {
        String[] keywords = {"查询", "订单", "编号", "id"};
        return terms.stream().anyMatch(term ->
                containsKeyword(term.word, keywords));
    }

    private static String extractOrderId(String input) {
        Matcher matcher = ID_PATTERN.matcher(input);
        return matcher.find() ? matcher.group(2) : null;
    }

    private static DateRange parseDateRange(String input) {
        Matcher matcher = DATE_RANGE_PATTERN.matcher(input);
        if (!matcher.find()) return null;

        int number = Integer.parseInt(matcher.group(1));
        String unit = matcher.group(2);

        LocalDate startDate;
        switch (unit) {
            case "个月":
            case "月":
                startDate = LocalDate.now().minusMonths(number);
                break;
            case "天":
            case "日":
                startDate = LocalDate.now().minusDays(number);
                break;
            case "周":
            case "星期":
                startDate = LocalDate.now().minusWeeks(number);
                break;
            default:
                return null;
        }

        return new DateRange(startDate.format(DATE_FORMAT));
    }

    private static String buildApiUrl(QueryParams params) {
        return String.format("http://localhost:8080/queryAlarm?id=%s&start_date=%s",
                params.orderId, params.dateRange.startDate);
    }

    private static String callApi(String url) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new RuntimeException("接口调用失败: " +
                            EntityUtils.toString(response.getEntity()));
                }
                return EntityUtils.toString(response.getEntity());
            }
        }
    }

    // 参数对象
    private static class QueryParams {
        String orderId;
        DateRange dateRange;

        QueryParams(String orderId, DateRange dateRange) {
            this.orderId = orderId;
            this.dateRange = dateRange;
        }
    }

    // 日期范围对象
    private static class DateRange {
        String startDate;

        DateRange(String startDate) {
            this.startDate = startDate;
        }
    }

    private static boolean containsKeyword(String word, String[] keywords) {
        for (String keyword : keywords) {
            if (word.contains(keyword)) return true;
        }
        return false;
    }

    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final Pattern ID_PATTERN = Pattern.compile("(编号|号码|id)[为是]?(\\d+)");
    private static final Pattern DATE_RANGE_PATTERN = Pattern.compile("最近(\\d+)(个月|月|天|日|周|星期)");
}